//
//  RegionSearchController.m
//  location
//
//  Created by Dongxiang Xu on 2025/9/17.
//

#import "RegionSearchController.h"
#import "RegionSearchTableViewCell.h"

@interface RegionSearchController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITextField *textField;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray<MKMapItem *> *mapItems;

@end

@implementation RegionSearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RealWhiteColor;
    [self initView];
}

- (void)initView
{
    UIView *inputView = [[UIView alloc] initWithFrame:CGRectMake(20, STATUSHEIGHT+4, SCREEN_WIDTH-94, 36)];
    inputView.layer.masksToBounds = YES;
    [inputView.layer setCornerRadius:10];
    inputView.backgroundColor = WhiteColor;
    [self.view addSubview:inputView];
    
    UIImageView *search = [[UIImageView alloc]initWithFrame:CGRectMake(5, (inputView.height-22)/2, 22, 22)];
    search.image = [UIImage imageNamed:@"search"];
    [inputView addSubview:search];
     
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(search.maxX+3, 0, inputView.width-search.maxX-11, inputView.height)];
    _textField.textColor = GraryHeavyLightColor;
    _textField.font = DEFAULT_FONT(15);
    _textField.placeholder = @"搜索地址";
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textField.returnKeyType = UIReturnKeySearch;
    _textField.enablesReturnKeyAutomatically = YES;
    _textField.delegate = self;
    [_textField becomeFirstResponder];
    [inputView addSubview:_textField];
    
    UIButton *cancle = [[UIButton alloc]initWithFrame:CGRectMake(inputView.maxX, STATUSHEIGHT, 74, 44)];
    [cancle setTitleColor:GraryHeavyLightColor forState:UIControlStateNormal];
    [cancle setTitle:@"取消" forState:UIControlStateNormal];
    [cancle.titleLabel setFont:REAL_MEDIUM_FONT(17)];
    [self.view addSubview:cancle];
    [[cancle rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-NAVHEIGHT) style:UITableViewStylePlain];
    _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    _tableView.estimatedRowHeight = 0;
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 15.0, *)) {
        _tableView.fillerRowHeight = 0;
        _tableView.sectionHeaderTopPadding = 0;
    }
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
    request.naturalLanguageQuery = textField.text;   
    request.region = self.region;

    MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:request];
    [search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
        if (error) {
            NSLog(@"搜索失败: %@", error.localizedDescription);
        } else {
            [self.textField resignFirstResponder];
            self.mapItems = [NSArray arrayWithArray:response.mapItems];
            [self.tableView reloadData];
        }
    }];
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.mapItems.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 76;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = @"RegionSearchTableViewCell";
    RegionSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[RegionSearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.title.text = self.mapItems[indexPath.row].name;
  
    if (self.mapItems[indexPath.row].placemark.thoroughfare) {
        cell.subTitle.text = [NSString stringWithFormat:@"%@%@",self.mapItems[indexPath.row].placemark.thoroughfare,self.mapItems[indexPath.row].placemark.subThoroughfare?self.mapItems[indexPath.row].placemark.thoroughfare:@""];
    }else{
        cell.subTitle.text =  [NSString stringWithFormat:@"%@%@",self.mapItems[indexPath.row].placemark.subLocality,self.mapItems[indexPath.row].placemark.name];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{   
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.RegionSearchBlock) {
            self.RegionSearchBlock(self.mapItems[indexPath.row]);
        }
    }];
}

@end
